package com.sgl.gk.scheduled;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.sg.comm.service.OpcUaServiceV2;
import com.sg.comm.service.SerialPortService;
import com.sgl.common.utils.DateUtils;
import com.sgl.common.utils.FileDownloadUtils;
import com.sgl.common.utils.StringUtils;
import com.sgl.common.utils.ZipUtils;
import com.sgl.gk.controller.vo.ExportDataTraceabilityVo;
import com.sgl.gk.controller.vo.GkProductionLineVo;
import com.sgl.gk.domain.*;
import com.sgl.gk.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:xec
 * @date:2022/11/18 16:12
 **/
//@Component
@Slf4j
@RestController
public class ScheduledTask {

    @Autowired
    GkStationEventMapper gkStationEventMapper;

    @Autowired
    GkStationConfigurationMapper gkStationConfigurationMapper;

    @Autowired
    GkStationConfigurationConnectMapper gkStationConfigurationConnectMapper;

    @Autowired
    GkStationConfigurationValuesMapper gkStationConfigurationValuesMapper;

    @Autowired
    GkStationMapper gkStationMapper;

    @Autowired
    GkProductMapper gkProductMapper;

    @Autowired
    GkProductionLineMapper gkProductionLineMapper;

    @Autowired
    GkStatisticsMapper gkStatisticsMapper;

    @Autowired
    GkEquipmentMapper gkEquipmentMapper;

    @DubboReference(version = "1.0.0", url = "dubbo://127.0.0.1:20880", check = false)
    private OpcUaServiceV2 opcUaServiceV2;

    //    @DubboReference(version = "1.0.0", url = "dubbo://192.168.0.107:20880", check = false)
    @DubboReference(version = "1.0.0", url = "dubbo://127.0.0.1:20880", check = false)
    private SerialPortService serialPortService;

    @Autowired
    GkSignalCommunicationMapper gkSignalCommunicationMapper;

    @Autowired
    GkSettingMapper gkSettingMapper;


    @Autowired
    GkDataValueLogMapper gkDataValueLogMapper;

    @Autowired
    GkStationConfigureTemplateMapper gkStationConfigureTemplateMapper;

    @Autowired
    GkStationConfigureTemplateInfoMapper gkStationConfigureTemplateInfoMapper;


    public static List<GkEquipment> gkEquipmentList = new ArrayList<>();


    public static Boolean isMatching = Boolean.TRUE;


    public static Boolean isMaching = false;

    public static String scanningBarCode = "";

    public static String barCodeStationName = "";


    @Value("${communication.mode}")
    public String communication;

    public void daTask() {

    }

    BufferedReader reader = null;
    BufferedWriter writer = null;


    Socket socket1 = null;

    static public BufferedReader bufferedReader = null;

    static public BufferedWriter bufferedWriter = null;

    @PostConstruct
    public void settingSocket() {
        if (communication.equals("socket")) {
            try {
                socket1 = new Socket("127.0.0.1", 8888);
                bufferedReader = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public static List<String> readScanningCodeList = new ArrayList<>();

    public static Boolean isScanning = false;


    @Scheduled(cron = "0 0 11 ? * *")
    @GetMapping("dataMigrationOne")
    public void dataMigrationOne(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        date = DateUtil.endOfDay(date);
        Date endtime = DateUtils.addWeeks(date, -2);
        List<GkStationConfigurationConnect> gkStationConfigurationConnectList = new ArrayList<>();
        GkStationConfigurationConnect minconfigurationConnect = null;
        GkDataValueLog gkDataValueLog = gkDataValueLogMapper.getMaxInfo();
        if (gkDataValueLog == null) {
            // 表示第一次移动数据  需要创建两张表
            Date lastTwoWeek = DateUtils.addWeeks(endtime, -1);
            lastTwoWeek = DateUtil.endOfWeek(lastTwoWeek);
            gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAtAll(lastTwoWeek, null);
            minconfigurationConnect = gkStationConfigurationConnectList.stream().min(Comparator.comparing(GkStationConfigurationConnect::getLastModifyAt)).get();
            String surfaceName = "value_" + 1;
            // 创建表
            GkDataValueLog table = createTable(surfaceName, minconfigurationConnect.getLastModifyAt(), lastTwoWeek);
            for (GkStationConfigurationConnect configurationConnect : gkStationConfigurationConnectList) {
                // 插入数据
                insertDate(surfaceName,configurationConnect.getId());
            }
            // 创建第二张表
            Date date1 = DateUtils.addDays(lastTwoWeek, 1);
            Date beginOfWeek = DateUtil.beginOfWeek(date1);
            Date endOfWeek = DateUtil.endOfWeek(date1);
            String format = simpleDateFormat.format(endOfWeek);
            try {
                endOfWeek = simpleDateFormat.parse(format);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            String surfaceName1 = "value_" + 2;
            gkDataValueLog = createTable(surfaceName1, beginOfWeek, endOfWeek);
        }
        // 每天存上两周数据
        Date startTime = DateUtil.beginOfWeek(endtime);
        endtime = DateUtil.endOfWeek(endtime);
        String format = simpleDateFormat.format(endtime);
        try {
            endtime = simpleDateFormat.parse(format);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAtAll(endtime, startTime);

        for (GkStationConfigurationConnect configurationConnect : gkStationConfigurationConnectList) {
            Date lastModifyAt = configurationConnect.getLastModifyAt();
            if (lastModifyAt.compareTo(gkDataValueLog.getDataStartTime())>=0&& lastModifyAt.compareTo(gkDataValueLog.getDataEndTime())<=0){
                insertDate(gkDataValueLog.getSurfaceName(),configurationConnect.getId());
            }else {
                // 插入数据
                String surfaceName = "value_" + (gkDataValueLog.getId().intValue() + 1);
                Date beginOfWeek = DateUtil.beginOfWeek(lastModifyAt);
                Date endOfWeek = DateUtil.endOfWeek(lastModifyAt);
                System.out.println("第三张表时间 beginOfWeek = " + beginOfWeek);
                System.out.println("endOfWeek = " + endOfWeek);
                gkDataValueLog = createTable(surfaceName,beginOfWeek,endOfWeek);
                insertDate(gkDataValueLog.getSurfaceName(),configurationConnect.getId());
            }
        }
    }


    @GetMapping("dataMigration")
    public void dataMigration() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        date = DateUtil.endOfDay(date);
        Date endtime = DateUtils.addWeeks(date, -2);
        List<GkStationConfigurationConnect> gkStationConfigurationConnectList = new ArrayList<>();
        GkStationConfigurationConnect minconfigurationConnect = null;
        GkDataValueLog gkDataValueLog = gkDataValueLogMapper.getMaxInfo();
        if (gkDataValueLog == null) {
            // 表示第一次移动数据  需要创建两张表
            Date lastTwoWeek = DateUtils.addWeeks(endtime, -1);
            lastTwoWeek = DateUtil.endOfWeek(lastTwoWeek);
            gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAtAll(lastTwoWeek, null);
            minconfigurationConnect = gkStationConfigurationConnectList.stream().min(Comparator.comparing(GkStationConfigurationConnect::getLastModifyAt)).get();
            String surfaceName = "value_" + 1;
            // 创建表
            GkDataValueLog table = createTable(surfaceName, minconfigurationConnect.getLastModifyAt(), lastTwoWeek);
            List<Long> connectIds = gkStationConfigurationConnectList.stream().map(GkStationConfigurationConnect::getId).collect(Collectors.toList());
            insertListDate(surfaceName, connectIds);

            // 创建第二张表
            Date date1 = DateUtils.addDays(lastTwoWeek, 1);
            Date beginOfWeek = DateUtil.beginOfWeek(date1);
            Date endOfWeek = DateUtil.endOfWeek(date1);
            String format = simpleDateFormat.format(endOfWeek);
            try {
                endOfWeek = simpleDateFormat.parse(format);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            String surfaceName1 = "value_" + 2;
            gkDataValueLog = createTable(surfaceName1, beginOfWeek, endOfWeek);
        }
        // 每天存上两周数据
        Date startTime = DateUtil.beginOfWeek(endtime);
        endtime = DateUtil.endOfWeek(endtime);
        String format = simpleDateFormat.format(endtime);
        try {
            endtime = simpleDateFormat.parse(format);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAtAll(endtime, startTime);

        for (GkStationConfigurationConnect configurationConnect : gkStationConfigurationConnectList) {
            Date lastModifyAt = configurationConnect.getLastModifyAt();
            if (!(lastModifyAt.compareTo(gkDataValueLog.getDataStartTime()) >= 0 && lastModifyAt.compareTo(gkDataValueLog.getDataEndTime()) <= 0)) {
                // 创建表
                String surfaceName = "value_" + (gkDataValueLog.getId().intValue() + 1);
                Date beginOfWeek = DateUtil.beginOfWeek(lastModifyAt);
                Date endOfWeek = DateUtil.endOfWeek(lastModifyAt);
                System.out.println("表创建时间 beginOfWeek = " + beginOfWeek);
                System.out.println("endOfWeek = " + endOfWeek);
                gkDataValueLog = createTable(surfaceName, beginOfWeek, endOfWeek);
                break;
            }
        }
        if (CollUtil.isNotEmpty(gkStationConfigurationConnectList)) {
            List<Long> collect = gkStationConfigurationConnectList.stream().map(GkStationConfigurationConnect::getId).collect(Collectors.toList());
            insertListDate(gkDataValueLog.getSurfaceName(), collect);
        }
    }

    @Scheduled(cron = "0 0 9 ? * *")
    @GetMapping("exportExcelToDay")
    public void exportExcelToDay() {
        Date date = new Date();
        // 导出一周内数据
        Date dayStart = DateUtils.addWeeks(date, -1);
        List<GkStationConfigurationConnect> gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAt(date, dayStart);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        // 得到了需要导出的conn
        if (gkStationConfigurationConnectList != null && gkStationConfigurationConnectList.size() > 0) {
            gkStationConfigurationConnectList = gkStationConfigurationConnectList.stream().filter(gkStationConfigurationConnect -> gkStationConfigurationConnect.getIsExport()==null||gkStationConfigurationConnect.getIsExport()==0).collect(Collectors.toList());
            // 找到模板产品对应的模板参数
            List<String> productNames = gkStationConfigurationConnectList.stream().map(GkStationConfigurationConnect::getProductName).collect(Collectors.toList());
            List<GkProduct> gkProducts = new ArrayList<>();
            if (CollUtil.isNotEmpty(productNames)) {
                gkProducts = gkProductMapper.selectByNames(productNames);
            }
            List<String> tempNames = gkProducts.stream().map(GkProduct::getTemplateName).collect(Collectors.toList());
            List<GkStationConfigureTemplate> gkStationConfigureTemplates = new ArrayList<>();
            List<Long> tempIds = new ArrayList<>();
            if (CollUtil.isNotEmpty(tempNames)) {
                gkStationConfigureTemplates = gkStationConfigureTemplateMapper.selectInfoByNames(tempNames);
                tempIds = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getId).collect(Collectors.toList());
            }
            Map<Long, List<GkStationConfigureTemplateInfo>> connIdTempInfoMap = new HashMap<>();
            if (CollUtil.isNotEmpty(tempIds)) {
                List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateIds(tempIds);
                Map<Long, List<GkStationConfigureTemplateInfo>> tempInfoByTempIdMap = gkStationConfigureTemplateInfos.parallelStream().collect(Collectors.groupingBy(GkStationConfigureTemplateInfo::getConfigureTemplateId));
                for (GkStationConfigurationConnect stationConfigurationConnect : gkStationConfigurationConnectList) {
                    List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfoList = new ArrayList<>();
                    for (GkProduct gkProduct : gkProducts) {
                        if (stationConfigurationConnect.getProductName() != null) {
                            if (stationConfigurationConnect.getProductName().equals(gkProduct.getName())) {
                                for (GkStationConfigureTemplate gkStationConfigureTemplate : gkStationConfigureTemplates) {
                                    if (gkStationConfigureTemplate.getName().equals(gkProduct.getTemplateName())) {
                                        gkStationConfigureTemplateInfoList.addAll(tempInfoByTempIdMap.get(gkStationConfigureTemplate.getId()));
                                    }
                                }
                            }
                        }
                    }
                    connIdTempInfoMap.put(stationConfigurationConnect.getId(), gkStationConfigureTemplateInfoList);
                }
            }
            List<GkStation> gkStations = gkStationMapper.allInfo();
            List<GkProductionLineVo> productionLineVos = gkProductionLineMapper.list(null);

            for (GkStationConfigurationConnect stationConfigurationConnect : gkStationConfigurationConnectList) {
                // 需要导出的值
                List<GkStationConfigurationValues> gkStationConfigurationValuesList = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectId(stationConfigurationConnect.getId());
                List<Long> configIds = gkStationConfigurationValuesList.stream().map(GkStationConfigurationValues::getStationConfigurationId).collect(Collectors.toList());
                // 导出的数据
                List<GkStationConfiguration> gkStationConfigurationList = new ArrayList<>();
                if (CollUtil.isNotEmpty(configIds)) {
                    gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByIds(configIds);
                }
                List<Map<String, Object>> mapList = new ArrayList<>();
                // 需要导出的模板信息
                List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = connIdTempInfoMap.get(stationConfigurationConnect.getId());
                String productName = stationConfigurationConnect.getProductName();
                String assemblyCode = stationConfigurationConnect.getAssemblyCode();
                String traceabilityCode = stationConfigurationConnect.getTraceabilityCode();
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
                String fileName = new String();
                Date createAt = stationConfigurationConnect.getLastModifyAt();
                String format = simpleDateFormat1.format(createAt);
                fileName = (StringUtils.isNotEmpty(productName) ? productName + "-" : "") + (StringUtils.isNotEmpty(assemblyCode) ? assemblyCode + "_" : "") + (StringUtils.isNotEmpty(traceabilityCode) ? traceabilityCode + "_" : "") + (format);
                for (GkStation gkStation : gkStations) {
                    Map<String, Object> map = new HashMap<>();
                    // 每个工位一张sheet
                    List<GkStationConfiguration> gkStationConfigurationVoList = new ArrayList<>();
                    for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
                        if (CollUtil.isNotEmpty(gkStationConfigureTemplateInfos)) {
                            for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                                if (gkStationConfiguration.getId().longValue() == gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()) {
                                    gkStationConfiguration.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                                    if (StringUtils.isNotEmpty(gkStationConfigureTemplateInfo.getTempConfigName())) {
                                        gkStationConfiguration.setDisplayName(gkStationConfigureTemplateInfo.getTempConfigName());
                                    }
                                    break;
                                }
                            }
                        } else {
                            gkStationConfiguration.setTempToUse(1);
                        }
                        if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                            if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)) {
                                for (GkStationConfigurationValues stationConfigurationValues : gkStationConfigurationValuesList) {
                                    if (stationConfigurationValues.getStationConfigurationId().longValue() == gkStationConfiguration.getId().longValue() && gkStationConfiguration.getTempToUse() != null && gkStationConfiguration.getTempToUse() == 1) {
                                        if (gkStationConfiguration.getResultConversion() == 1) {
                                            String value = "";
                                            switch (stationConfigurationValues.getValue()) {
                                                case "0":
                                                    ;
                                                case "0.0":
                                                    value = gkStationConfiguration.getZeroValue();
                                                    break;
                                                case "1":
                                                case "1.0":
                                                    value = gkStationConfiguration.getOneValue();
                                                    break;
                                                case "2":
                                                case "2.0":
                                                    value = gkStationConfiguration.getTwoValue();
                                                    break;
                                                case "3":
                                                case "3.0":
                                                    value = gkStationConfiguration.getThreeValue();
                                                    break;
                                                case "4":
                                                case "4.0":
                                                    value = gkStationConfiguration.getFourValue();
                                                    break;
                                                case "5":
                                                case "5.0":
                                                    value = gkStationConfiguration.getFiveValue();
                                                    break;
                                            }
                                            if (!StringUtils.isEmpty(value)) {
                                                stationConfigurationValues.setValue(value);
                                            }
                                        }
                                        gkStationConfiguration.setSaveValue(stationConfigurationValues.getValue());
                                        gkStationConfigurationVoList.add(gkStationConfiguration);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (CollUtil.isNotEmpty(gkStationConfigurationList)) {
                        String sheetName = new String();
                        for (GkProductionLineVo productionLineVo : productionLineVos) {
                            if (gkStation.getProductionLineId().longValue() == productionLineVo.getId().longValue()) {
                                sheetName = productionLineVo.getName() + "#" + gkStation.getName();
                                sheetName = sheetName.replace("/", "").replace("\\", "");
                            }
                        }
                        map.put("sheetName", sheetName);
                        map.put("sheetData", gkStationConfigurationVoList);
                        if (gkStationConfigurationVoList.size() > 0) {
                            mapList.add(map);
                        }
                    }
                }
                if (mapList.size() > 0) {
                    try {
                        String ym = dateFormat.format(createAt);
                        Boolean isExport = exportSheets(mapList, fileName, "d:/sg/excel/" + ym + "/");
                        if (isExport) {
                            stationConfigurationConnect.setIsExport(1);
                            gkStationConfigurationConnectMapper.edit(stationConfigurationConnect);
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    @GetMapping("exportHistory")
    public void exportHistory() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        // 导出今天之前的数据
        List<GkStationConfigurationConnect> gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAt(date, null);
        gkStationConfigurationConnectList = gkStationConfigurationConnectList.stream().filter(gkStationConfigurationConnect -> gkStationConfigurationConnect.getIsExport() == null || gkStationConfigurationConnect.getIsExport() == 0).collect(Collectors.toList());
        // 得到了需要导出的conn
        if (gkStationConfigurationConnectList != null && gkStationConfigurationConnectList.size() > 0) {
            // 找到模板产品对应的模板参数
            List<String> productNames = gkStationConfigurationConnectList.stream().map(GkStationConfigurationConnect::getProductName).collect(Collectors.toList());
            List<GkProduct> gkProducts = gkProductMapper.selectByNames(productNames);
            List<String> tempNames = gkProducts.stream().map(GkProduct::getTemplateName).collect(Collectors.toList());
            List<GkStationConfigureTemplate> gkStationConfigureTemplates = new ArrayList<>();
            List<Long> tempIds = new ArrayList<>();
            if (CollUtil.isNotEmpty(tempNames)) {
                gkStationConfigureTemplates = gkStationConfigureTemplateMapper.selectInfoByNames(tempNames);
                tempIds = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getId).collect(Collectors.toList());
            }
            Map<Long, List<GkStationConfigureTemplateInfo>> connIdTempInfoMap = new HashMap<>();
            if (CollUtil.isNotEmpty(tempIds)) {
                List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateIds(tempIds);
                Map<Long, List<GkStationConfigureTemplateInfo>> tempInfoByTempIdMap = gkStationConfigureTemplateInfos.parallelStream().collect(Collectors.groupingBy(GkStationConfigureTemplateInfo::getConfigureTemplateId));
                for (GkStationConfigurationConnect stationConfigurationConnect : gkStationConfigurationConnectList) {
                    List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfoList = new ArrayList<>();
                    for (GkProduct gkProduct : gkProducts) {
                        if (stationConfigurationConnect.getProductName() != null) {
                            if (stationConfigurationConnect.getProductName().equals(gkProduct.getName())) {
                                for (GkStationConfigureTemplate gkStationConfigureTemplate : gkStationConfigureTemplates) {
                                    if (gkStationConfigureTemplate.getName().equals(gkProduct.getTemplateName())) {
                                        gkStationConfigureTemplateInfoList.addAll(tempInfoByTempIdMap.get(gkStationConfigureTemplate.getId()));
                                    }
                                }
                            }
                        }
                    }
                    connIdTempInfoMap.put(stationConfigurationConnect.getId(), gkStationConfigureTemplateInfoList);
                }
            }
            List<GkStation> gkStations = gkStationMapper.allInfo();
            List<GkProductionLineVo> productionLineVos = gkProductionLineMapper.list(null);
            List<GkDataValueLog> gkDataValueLogList = gkDataValueLogMapper.selectAll();
            for (GkStationConfigurationConnect stationConfigurationConnect : gkStationConfigurationConnectList) {
                // 需要导出的值
                List<GkStationConfigurationValues> gkStationConfigurationValuesList = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectId(stationConfigurationConnect.getId());
                if (CollUtil.isNotEmpty(gkDataValueLogList)){
                    for (GkDataValueLog gkDataValueLog : gkDataValueLogList) {
                        List<GkStationConfigurationValues> gkStationConfigurationValue = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectIdAndTableName(gkDataValueLog.getSurfaceName(), stationConfigurationConnect.getId());
                        if (CollUtil.isNotEmpty(gkStationConfigurationValue)){
                            gkStationConfigurationValuesList.addAll(gkStationConfigurationValue);
                        }
                    }
                }
                List<GkStationConfiguration> gkStationConfigurationList = new ArrayList<>();
                if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)) {
                    List<Long> configIds = gkStationConfigurationValuesList.stream().map(GkStationConfigurationValues::getStationConfigurationId).collect(Collectors.toList());
                    // 导出的数据
                    gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByIds(configIds);
                }
                List<Map<String, Object>> mapList = new ArrayList<>();
                // 需要导出的模板信息
                List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = connIdTempInfoMap.get(stationConfigurationConnect.getId());
                String productName = stationConfigurationConnect.getProductName();
                String assemblyCode = stationConfigurationConnect.getAssemblyCode();
                String traceabilityCode = stationConfigurationConnect.getTraceabilityCode();
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
                String fileName = new String();
                Date createAt = stationConfigurationConnect.getLastModifyAt();
                String format = simpleDateFormat1.format(createAt);
                fileName = (StringUtils.isNotEmpty(productName) ? productName + "-" : "") + (StringUtils.isNotEmpty(assemblyCode) ? assemblyCode + "_" : "") + (StringUtils.isNotEmpty(traceabilityCode) ? traceabilityCode + "_" : "") + (format);
                for (GkStation gkStation : gkStations) {
                    Map<String, Object> map = new HashMap<>();
                    // 每个工位一张sheet
                    List<GkStationConfiguration> gkStationConfigurationVoList = new ArrayList<>();
                    for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
                        if (CollUtil.isNotEmpty(gkStationConfigureTemplateInfos)) {
                            for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                                if (gkStationConfiguration.getId().longValue() == gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()) {
                                    gkStationConfiguration.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                                    if (StringUtils.isNotEmpty(gkStationConfigureTemplateInfo.getTempConfigName())) {
                                        gkStationConfiguration.setDisplayName(gkStationConfigureTemplateInfo.getTempConfigName());
                                    }
                                    break;
                                }
                            }
                        } else {
                            gkStationConfiguration.setTempToUse(1);
                        }
                        if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                            if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)) {
                                for (GkStationConfigurationValues stationConfigurationValues : gkStationConfigurationValuesList) {
                                    if (stationConfigurationValues.getStationConfigurationId().longValue() == gkStationConfiguration.getId().longValue() && gkStationConfiguration.getTempToUse() != null && gkStationConfiguration.getTempToUse() == 1) {
                                        if (gkStationConfiguration.getResultConversion() == 1) {
                                            String value = "";
                                            switch (stationConfigurationValues.getValue()) {
                                                case "0":
                                                    ;
                                                case "0.0":
                                                    value = gkStationConfiguration.getZeroValue();
                                                    break;
                                                case "1":
                                                case "1.0":
                                                    value = gkStationConfiguration.getOneValue();
                                                    break;
                                                case "2":
                                                case "2.0":
                                                    value = gkStationConfiguration.getTwoValue();
                                                    break;
                                                case "3":
                                                case "3.0":
                                                    value = gkStationConfiguration.getThreeValue();
                                                    break;
                                                case "4":
                                                case "4.0":
                                                    value = gkStationConfiguration.getFourValue();
                                                    break;
                                                case "5":
                                                case "5.0":
                                                    value = gkStationConfiguration.getFiveValue();
                                                    break;
                                            }
                                            if (!StringUtils.isEmpty(value)) {
                                                stationConfigurationValues.setValue(value);
                                            }
                                        }
                                        gkStationConfiguration.setSaveValue(stationConfigurationValues.getValue());
                                        gkStationConfigurationVoList.add(gkStationConfiguration);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (CollUtil.isNotEmpty(gkStationConfigurationList)) {
                        String sheetName = new String();
                        for (GkProductionLineVo productionLineVo : productionLineVos) {
                            if (gkStation.getProductionLineId().longValue() == productionLineVo.getId().longValue()) {
                                sheetName = productionLineVo.getName() + "#" + gkStation.getName();
                                sheetName = sheetName.replace("/", "").replace("\\", "");
                            }
                        }
                        map.put("sheetName", sheetName);
                        map.put("sheetData", gkStationConfigurationVoList);
                        if (gkStationConfigurationVoList.size() > 0) {
                            mapList.add(map);
                        }
                    }
                }
                if (mapList.size() > 0) {
                    try {
                        String ym = dateFormat.format(createAt);
                        Boolean isExport = exportSheets(mapList, fileName, "d:/sg/excel/" + ym + "/");
                        if (isExport) {
                            stationConfigurationConnect.setIsExport(1);
                            gkStationConfigurationConnectMapper.edit(stationConfigurationConnect);
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    @GetMapping("BatchExport")
    public void BatchExport() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        // 导出今天之前的数据
        List<GkStationConfigurationConnect> gkStationConfigurationConnectList = gkStationConfigurationConnectMapper.selectByLastModifyAt(date, null);
        gkStationConfigurationConnectList = gkStationConfigurationConnectList.stream().filter(gkStationConfigurationConnect -> gkStationConfigurationConnect.getIsExport() == null || gkStationConfigurationConnect.getIsExport() == 0).collect(Collectors.toList());
        List<GkStationConfigurationConnect> gkStationConfigurationConnects = gkStationConfigurationConnectList;
        List<GkDataValueLog> gkDataValueLogList = gkDataValueLogMapper.selectAll();
        if (gkStationConfigurationConnects != null && gkStationConfigurationConnects.size() > 0) {
            int allTotal = gkStationConfigurationConnects.size();
            int size = 200;
            int allLoop = allTotal / size;
            List<File> fileList = new ArrayList<>();
            log.info("总数：{},总循环：{}", allTotal, allLoop);
            for (int i = 0; i < allLoop + 1; i++) {
                List<GkStationConfigurationConnect> gkStationConfigurationConnects1 = new ArrayList<>();
                gkStationConfigurationConnects1 = gkStationConfigurationConnects.stream().skip(i * size).limit(size).collect(Collectors.toList());

                List<Long> connectIds = gkStationConfigurationConnects1.stream().map(GkStationConfigurationConnect::getId).collect(Collectors.toList());
                // 需要导出的conn数据
                List<GkStationConfigurationValues> exportValues = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectIds(connectIds);
                if (CollUtil.isNotEmpty(gkDataValueLogList)){
                    for (GkDataValueLog gkDataValueLog : gkDataValueLogList) {
                        List<GkStationConfigurationValues> gkStationConfigurationValuesList = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectIdsAndTableName(gkDataValueLog.getSurfaceName(), connectIds);
                        if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)){
                            exportValues.addAll(gkStationConfigurationValuesList);
                        }
                    }
                }
                // 找到模板产品对应的模板参数
                List<String> productNames = gkStationConfigurationConnects1.stream().map(GkStationConfigurationConnect::getProductName).collect(Collectors.toList());
                List<GkProduct> gkProducts = gkProductMapper.selectByNames(productNames);
                List<String> tempNames = gkProducts.stream().map(GkProduct::getTemplateName).collect(Collectors.toList());
                List<GkStationConfigureTemplate> gkStationConfigureTemplates = new ArrayList<>();
                List<Long> tempIds = new ArrayList<>();
                if (CollUtil.isNotEmpty(tempNames)) {
                    gkStationConfigureTemplates = gkStationConfigureTemplateMapper.selectInfoByNames(tempNames);
                    tempIds = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getId).collect(Collectors.toList());
                }
                Map<Long, List<GkStationConfigureTemplateInfo>> connIdTempInfoMap = new HashMap<>();
                if (CollUtil.isNotEmpty(tempIds)) {
                    List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateIds(tempIds);
                    Map<Long, List<GkStationConfigureTemplateInfo>> tempInfoByTempIdMap = gkStationConfigureTemplateInfos.parallelStream().collect(Collectors.groupingBy(GkStationConfigureTemplateInfo::getConfigureTemplateId));
                    for (GkStationConfigurationConnect stationConfigurationConnect : gkStationConfigurationConnects1) {
                        List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfoList = new ArrayList<>();
                        for (GkProduct gkProduct : gkProducts) {
                            if (stationConfigurationConnect.getProductName() != null) {
                                if (stationConfigurationConnect.getProductName().equals(gkProduct.getName())) {
                                    for (GkStationConfigureTemplate gkStationConfigureTemplate : gkStationConfigureTemplates) {
                                        if (gkStationConfigureTemplate.getName().equals(gkProduct.getTemplateName())) {
                                            gkStationConfigureTemplateInfoList.addAll(tempInfoByTempIdMap.get(gkStationConfigureTemplate.getId()));
                                        }
                                    }
                                }
                            }
                        }
                        connIdTempInfoMap.put(stationConfigurationConnect.getId(), gkStationConfigureTemplateInfoList);
                    }
                }
                Map<Long, List<GkStationConfigurationValues>> connIdConfigValueMap = new HashMap<>();
                connIdConfigValueMap = exportValues.parallelStream().collect(Collectors.groupingBy(GkStationConfigurationValues::getStationConfigurationConnectId));


                List<Long> configIds = exportValues.stream().map(GkStationConfigurationValues::getStationConfigurationId).collect(Collectors.toList());
                // 导出的数据
                List<GkStationConfiguration> gkStationConfigurationList = new ArrayList<>();
                if (CollUtil.isNotEmpty(configIds)) {
                    gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByIds(configIds);
                }
//                List<Long> stationIds = gkStationConfigurationList.stream().map(GkStationConfiguration::getStationId).distinct().collect(Collectors.toList());
                List<GkStation> gkStations = gkStationMapper.allInfo();
                List<GkProductionLineVo> productionLineVos = gkProductionLineMapper.list(null);
                for (GkStationConfigurationConnect stationConfigurationConnect : gkStationConfigurationConnects1) {
                    List<Map<String, Object>> mapList = new ArrayList<>();
                    // 需要导出的值
                    List<GkStationConfigurationValues> gkStationConfigurationValuesList = connIdConfigValueMap.get(stationConfigurationConnect.getId());
                    // 需要导出的模板信息
                    List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = connIdTempInfoMap.get(stationConfigurationConnect.getId());
                    String productName = stationConfigurationConnect.getProductName();
                    String assemblyCode = stationConfigurationConnect.getAssemblyCode();
                    String traceabilityCode = stationConfigurationConnect.getTraceabilityCode();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String fileName = new String();
                    Date createAt = stationConfigurationConnect.getCreateAt();
                    String format = simpleDateFormat.format(createAt);
                    fileName = (StringUtils.isNotEmpty(productName) ? productName + "-" : "") + (StringUtils.isNotEmpty(assemblyCode) ? assemblyCode + "_" : "") + (StringUtils.isNotEmpty(traceabilityCode) ? traceabilityCode + "_" : "") + (format);
                    for (GkStation gkStation : gkStations) {
                        Map<String, Object> map = new HashMap<>();
                        // 每个工位一张sheet
                        List<GkStationConfiguration> gkStationConfigurationVoList = new ArrayList<>();
                        for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
                            if (CollUtil.isNotEmpty(gkStationConfigureTemplateInfos)) {
                                for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                                    if (gkStationConfiguration.getId().longValue() == gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()) {
                                        gkStationConfiguration.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                                        if (StringUtils.isNotEmpty(gkStationConfigureTemplateInfo.getTempConfigName())) {
                                            gkStationConfiguration.setDisplayName(gkStationConfigureTemplateInfo.getTempConfigName());
                                        }
                                        break;
                                    }
                                }
                            } else {
                                gkStationConfiguration.setTempToUse(1);
                            }
                            if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                                if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)) {
                                    for (GkStationConfigurationValues stationConfigurationValues : gkStationConfigurationValuesList) {
                                        if (stationConfigurationValues.getStationConfigurationId().longValue() == gkStationConfiguration.getId().longValue() && gkStationConfiguration.getTempToUse() != null && gkStationConfiguration.getTempToUse() == 1) {
                                            if (gkStationConfiguration.getResultConversion() == 1) {
                                                String value = "";
                                                switch (stationConfigurationValues.getValue()) {
                                                    case "0":
                                                        ;
                                                    case "0.0":
                                                        value = gkStationConfiguration.getZeroValue();
                                                        break;
                                                    case "1":
                                                    case "1.0":
                                                        value = gkStationConfiguration.getOneValue();
                                                        break;
                                                    case "2":
                                                    case "2.0":
                                                        value = gkStationConfiguration.getTwoValue();
                                                        break;
                                                    case "3":
                                                    case "3.0":
                                                        value = gkStationConfiguration.getThreeValue();
                                                        break;
                                                    case "4":
                                                    case "4.0":
                                                        value = gkStationConfiguration.getFourValue();
                                                        break;
                                                    case "5":
                                                    case "5.0":
                                                        value = gkStationConfiguration.getFiveValue();
                                                        break;
                                                }
                                                if (!StringUtils.isEmpty(value)) {
                                                    stationConfigurationValues.setValue(value);
                                                }
                                            }
                                            gkStationConfiguration.setSaveValue(stationConfigurationValues.getValue());
                                            gkStationConfigurationVoList.add(gkStationConfiguration);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (CollUtil.isNotEmpty(gkStationConfigurationList)) {
                            String sheetName = new String();
                            for (GkProductionLineVo productionLineVo : productionLineVos) {
                                if (gkStation.getProductionLineId().longValue() == productionLineVo.getId().longValue()) {
                                    sheetName = productionLineVo.getName() + "#" + gkStation.getName();
                                    sheetName = sheetName.replace("/", "").replace("\\", "");
                                }
                            }
                            map.put("sheetName", sheetName);
                            map.put("sheetData", gkStationConfigurationVoList);
                            if (gkStationConfigurationVoList.size() > 0) {
                                mapList.add(map);
                            }
                        }
                    }
                    if (mapList.size() > 0) {
                        try {
                            String ym = dateFormat.format(createAt);
                            Boolean isExport = exportSheets(mapList, fileName, "d:/sg/excel/" + ym + "/");
                            if (isExport) {
                                stationConfigurationConnect.setIsExport(1);
                                gkStationConfigurationConnectMapper.edit(stationConfigurationConnect);
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                    }
                }

            }
        }
    }

    public GkDataValueLog createTable(String tableName, Date startTime, Date endTime) {
        // 创建表
        gkDataValueLogMapper.createSurface(tableName);
        GkDataValueLog gkDataValueLog = new GkDataValueLog();
        gkDataValueLog.setDataStartTime(startTime);
        gkDataValueLog.setDataEndTime(endTime);
        gkDataValueLog.setSurfaceName(tableName);
        // 增加记录
        gkDataValueLogMapper.insert(gkDataValueLog);
        return gkDataValueLog;
    }

    public void insertDate(String tableName, Long connectId) {
        // 查询数据
        List<GkStationConfigurationValues> gkStationConfigurationValuesList = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectId(connectId);
        if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)) {
            // 转移数据
            gkDataValueLogMapper.saveListValues(tableName, gkStationConfigurationValuesList);
            // 删除数据
            List<Long> collect = gkStationConfigurationValuesList.stream().map(GkStationConfigurationValues::getId).collect(Collectors.toList());
            gkStationConfigurationValuesMapper.deleteByIds(collect);
        }
    }

    public void insertListDate(String tableName, List<Long> connectIds) {
        int size = 50;
        int allTotal = connectIds.size();
        int allLoop = allTotal / size;
        for (int i = 0; i < allLoop + 1; i++) {
            List<Long> collect = connectIds.stream().skip(i * size).limit(size).collect(Collectors.toList());
            List<GkStationConfigurationValues> gkStationConfigurationValuesList = gkStationConfigurationValuesMapper.selectByStationConfigurationConnectIds(collect);
            if (CollUtil.isNotEmpty(gkStationConfigurationValuesList)) {
                gkDataValueLogMapper.saveListValues(tableName, gkStationConfigurationValuesList);
                // 删除数据
                List<Long> valueIds= gkStationConfigurationValuesList.stream().map(GkStationConfigurationValues::getId).collect(Collectors.toList());
                gkStationConfigurationValuesMapper.deleteByIds(valueIds);
            }
        }

    }

    public Boolean exportSheets(List<Map<String, Object>> mapList, String fileName, String tempDir) {
        Workbook workbook = null;
        try {
            List<Map<String, Object>> maps = new ArrayList<>();
            for (Map<String, Object> map : mapList) {
                ExportParams exportParams = new ExportParams();
                Object sheetName = map.get("sheetName");
                Object sheetData = map.get("sheetData");
                exportParams.setSheetName(sheetName.toString());
                List<GkStationConfiguration> gkStationConfigurationVos = JSON.parseArray(JSON.toJSONString(sheetData), GkStationConfiguration.class);

                List<ExportDataTraceabilityVo> list = new ArrayList<>();
                if (CollUtil.isNotEmpty(gkStationConfigurationVos)) {
                    for (GkStationConfiguration gkStationConfigurationVo : gkStationConfigurationVos) {
                        ExportDataTraceabilityVo exportDataTraceabilityVo = new ExportDataTraceabilityVo();
                        exportDataTraceabilityVo.setDataType(gkStationConfigurationVo.getDataType());
                        exportDataTraceabilityVo.setDisplayName(gkStationConfigurationVo.getDisplayName());
                        exportDataTraceabilityVo.setSaveValue(gkStationConfigurationVo.getSaveValue());
                        exportDataTraceabilityVo.setNameSpaces(gkStationConfigurationVo.getNameSpaces());
                        exportDataTraceabilityVo.setVariableAddress(gkStationConfigurationVo.getVariableAddress());
                        exportDataTraceabilityVo.setVariableName(gkStationConfigurationVo.getVariableName());
                        exportDataTraceabilityVo.setVariableRemarks(gkStationConfigurationVo.getVariableRemarks());
                        exportDataTraceabilityVo.setVariableComments(gkStationConfigurationVo.getVariableComments());
                        list.add(exportDataTraceabilityVo);
                    }
                }
                list = list.stream().sorted((s1, s2) -> s1.getVariableName().toLowerCase().contains("barcode") ? -1 : s2.getVariableName().toLowerCase().contains("barcode") ? 1 : 0).collect(Collectors.toList());
                Map<String, Object> exportMap = new HashMap<>();
                exportMap.put("title", exportParams);
                exportMap.put("entity", ExportDataTraceabilityVo.class);
                exportMap.put("data", list);
                maps.add(exportMap);
            }

            FileDownloadUtils.createFile(tempDir);
            File file = new File(tempDir + fileName + ".xls");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            workbook = ExcelExportUtil.exportExcel(maps, ExcelType.HSSF);
            workbook.write(fileOutputStream);
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (workbook != null) {
                try {
                    //强行关流
                    workbook.close();
                } catch (IOException e) {
                    return true;
                }
            }
        }
    }
}